package com.qxy.hgz.util;


import com.qxy.hgz.rank.model.VideoType;

import org.json.JSONException;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestUtil {
    private static final OkHttpClient client = new OkHttpClient();

    public static RequestBody buildRequestBody(HashMap<String,String> body) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : body.keySet()) {
            String value = body.get(key);
            if (value != null) {
                builder.add(key,value);
            }
        }
        return builder.build();
    }

    public static void GET(String fullUrl,HashMap<String,String> requestHeaders,
                           HashMap<String,String> requestArgs,InternetHandler action) {

        Request.Builder builder = new Request.Builder();
        if (requestArgs != null) {
            StringBuilder sb = new StringBuilder().append(fullUrl);
            sb.append("?");
            for (String key: requestHeaders.keySet()) {
                String value = requestHeaders.get(key);
                if (value != null) {
                    sb.append(key).append("=").append(value).append("&");
                }
            }
            String url = sb.toString();
            builder.url(url.substring(0,sb.length()-1));
        }else {
            builder.url(fullUrl);
        }

        if (requestHeaders != null) {
            for (String key: requestHeaders.keySet()) {
                String value = requestHeaders.get(key);
                if (value != null) {
                    builder.addHeader(key,value);
                }
            }
        }
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    action.handleData(response);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    public static void POST(String fullUrl,HashMap<String,String> requestHeaders,
                            HashMap<String,String> requestBody,InternetHandler action) {

        Request.Builder builder = new Request.Builder().url(fullUrl);
        if (requestBody != null) {
            RequestBody body = buildRequestBody(requestBody);
            builder.post(body);
        }

        if (requestHeaders != null) {
            for (String key: requestHeaders.keySet()) {
                String value = requestHeaders.get(key);
                if (value != null) {
                    builder.addHeader(key,value);
                }
            }
        }

        Request request = builder.build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    action.handleData(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    /**
     * 获取access_token
     */
    public static void getAccessToken(String fullUrl, String authCode,InternetHandler action) {
        HashMap<String,String> postBodyMap = new HashMap<>();
        postBodyMap.put("client_secret",ConfigInfo.CLIENT_SECRET);
        postBodyMap.put("code",authCode);
        postBodyMap.put("grant_type","authorization_code");
        postBodyMap.put("client_key",ConfigInfo.CLIENT_KEY);

        HashMap<String,String> headMap = new HashMap<>();
        headMap.put("Content-Type","application/x-www-form-urlencoded");
        POST(fullUrl,headMap,postBodyMap,action);
    }


    public static void getVideoListVersion(String fullUrl, int cursor, int count, VideoType videoType,
                                           String clientToken,InternetHandler action) {
        HashMap<String,String> argsMap = new HashMap<>();
        argsMap.put("cursor",String.valueOf(cursor));
        argsMap.put("count",String.valueOf(count));
        argsMap.put("type",String.valueOf(videoType.getValue()));

        HashMap<String,String> headMap = new HashMap<>();
        headMap.put("Content-Type","application/json");
        headMap.put("access-token",clientToken);
        GET(fullUrl,headMap,argsMap,action);
    }


    public static void getClientToken(String fullUrl,InternetHandler action) {
        HashMap<String,String> postBodyMap = new HashMap<>();
        postBodyMap.put("client_key",ConfigInfo.CLIENT_KEY);
        postBodyMap.put("client_secret",ConfigInfo.CLIENT_SECRET);
        postBodyMap.put("grant_type","client_credential");

        HashMap<String,String> headMap = new HashMap<>();
        headMap.put("Content-Type","multipart/form-data");

        POST(fullUrl,headMap,postBodyMap,action);

    }



    public static void getFilmList(String fullUrl,String clientToken,VideoType videoType,InternetHandler action) {

        HashMap<String,String> argsMap = new HashMap<>();
        argsMap.put("type",String.valueOf(videoType.getValue()));

        HashMap<String,String> headMap = new HashMap<>();
        headMap.put("Content-Type","application/json");
        headMap.put("access-token",clientToken);

        GET(fullUrl,headMap,argsMap,action);
    }

    public static void getUserData(String fullUrl,String accessToken,String openId,InternetHandler action) {
        HashMap<String,String> requestHeads = new HashMap<>();
        requestHeads.put("Content-Type","application/json");
        requestHeads.put("access-token",accessToken);

        HashMap<String,String> requestBody = new HashMap<>();
        requestBody.put("access_token",accessToken);
        requestBody.put("open_id",openId);

        POST(fullUrl,requestHeads,requestBody,action);
    }


    //测试请求
    public static void test(String fullUrl,InternetHandler action) {
        GET(fullUrl,null,null,action);
    }
}
